﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Xml;
using System.Collections;


namespace TelephoneDirectory
{
    class MdiMenu
    {
        static List<Phone> listphone = new List<Phone>();
        static SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
        const string filename = "telephone.xml";

        //static int number;
        static int pos;
       // create menu
        static void Menu()
        {
            Console.WriteLine("=========================================================");
            Console.WriteLine("||          CHUC NANG DNAH BA DIEN THOAI               ||");
            Console.WriteLine("=========================================================");
            Console.WriteLine("||                   1. Them moi thue bao...           ||");
            Console.WriteLine("||                   2. Sua thong tin thue bao...      ||");
            Console.WriteLine("||                   3. Xoa thue bao...                ||");
            Console.WriteLine("||                   4. Tim kiem theo ten...           ||");
            Console.WriteLine("||                   5. Tim kiem theo so dien thoai... ||");
            Console.WriteLine("||                   6. Xem danh sach thue bao...      ||");
            Console.WriteLine("||                   7. Thoat...                       ||");
            Console.WriteLine("=========================================================");
            Console.Write("Chon chuc nang:");
        }

        // create file xml
        static void CreateFile()
        {
            XmlTextWriter write = new XmlTextWriter(filename, Encoding.UTF8);
            write.WriteStartDocument(true);
            write.Formatting = Formatting.Indented;
            write.Indentation = 5;
            write.WriteStartElement("contacts");           
            write.WriteEndElement();
            write.WriteEndDocument();
            write.Close();
        }
      
       
        //=================================================================================================
        // insert one element into file xml
        static public void insert()
        {
            int i = 0;
            int number = 0;
             string _Name, _Code, _Address,choose;
             
             do
             {
                 if (i > 0)
                 {
                     if (i == 1)
                         Console.Write("\t\tTen thue bao khong qua 30 ky tu!");
                     Console.Write("\t\tNhap lai ten : ");
                 }
                 else

                     Console.Write("Moi nhap ten : ");
                 _Name = Console.ReadLine();
                 i++;
             }
             while (_Name.Length > 30);
             i = 0;
            //code
             do
             {
                 if (i > 0)
                 {
                     if (i == 1)
                         Console.Write("\t\tMa vung thue bao khong qua 5 ky tu!");
                     Console.Write("\t\tNhap lai ma vung : ");
                 }
                 else
                     Console.Write(" Moi nhap ma vung : ");
                 _Code = Console.ReadLine();
                 i++;
             }
             while (_Code.Length > 5);
            //address
             i = 0;
             do
             {
                 if (i > 0)
                 {
                     if (i == 1)
                         Console.Write("\t\tDia chi thue bao khong qua 50 ky tu!");
                     Console.Write("\t\tNhap lai dia chi : ");
                 }
                 else
                     Console.Write(" Moi nhap dia chi : ");
                 _Address = Console.ReadLine();
                 i++;
             }
             while (_Address.Length > 50);
            //number
             i = 0;
             do
             {
                 try
                 {
                     if (i > 0)
                     {
                         if (i == 1)
                             Console.Write("\t\tSo dien thoai nam trong khoang 4000000->4999999!");
                         Console.Write("\t\tNhap lai so dien thoai : ");
                     }
                     else
                         Console.Write(" Moi nhap so dien thoai : ");
                     i++;
                     number = Convert.ToInt32(Console.ReadLine());
                    
                 }
                 catch (Exception ex)
                 {
                 }
             }
             while (number < 4000000 || number > 4999999);
             const string msgQuestionInsert = " Ban co dong y them moi thue bao khong(Y/N?):";

             Console.Write(msgQuestionInsert);
             choose = Console.ReadKey().KeyChar.ToString();
             if ((choose == "y") || (choose == "Y"))
             {
                 Phone phone = new Phone(_Name, _Code, _Address, number.ToString());
                 add(phone, filename);
                 Sort(listphone);//
                 Console.WriteLine(" Them moi thanh cong");
             }
             if ((choose == "n") || (choose == "N"))
             {
                 menu();
             }
        }
        //==========
        // add one node to file xml
        public static void add(Phone phone,string _filename)
        {
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(_filename);
            
            XmlElement nodephone= myDoc.CreateElement("Phone");
            XmlElement phoneName = myDoc.CreateElement("Name");
            XmlElement phoneCode = myDoc.CreateElement("Code");
            XmlElement phoneAddress = myDoc.CreateElement("Address");
            XmlElement PhoneNumber = myDoc.CreateElement("Number");

            phoneName.InnerText = phone.Name;
            phoneCode.InnerText = phone.Code;
            phoneAddress.InnerText = phone.Address;
            PhoneNumber.InnerText = phone.Number;

            nodephone.AppendChild(phoneName);
            nodephone.AppendChild(phoneCode);
            nodephone.AppendChild(phoneAddress);
            nodephone.AppendChild(PhoneNumber);
            myDoc.DocumentElement.AppendChild(nodephone);

            myDoc.Save(_filename);
        }
        //===========
        // convert from list to file xml
        public static void ListToXml(List<Phone> listphone)
        {
           
            foreach (Phone phone in listphone)
            {              
                add(phone,filename);
            }
        }
        //========
        // convert from file xml to list
        public static List<Phone> XmlToList(string _filename)
        {
            List<Phone> listphone = new List<Phone>();
            XmlDocument doc = new XmlDocument();
            doc.Load(_filename);

            XmlNodeList nodelist = doc.GetElementsByTagName("Name");
            int i = 0;
            foreach (XmlNode node in nodelist)
            {
                string _name, _code, _address, _number;
                XmlNode nodecode = doc.GetElementsByTagName("Code")[i];
                XmlNode nodeaddress = doc.GetElementsByTagName("Address")[i];
                XmlNode nodenumber = doc.GetElementsByTagName("Number")[i];

                _name = node.ChildNodes[0].Value;
                _code = nodecode.ChildNodes[0].Value;
                _address = nodeaddress.ChildNodes[0].Value;
                _number = nodenumber.ChildNodes[0].Value;

                Phone phone = new Phone(_name, _code, _address, _number);
                listphone.Add(phone);
                i++;
            }
            return listphone;
        }
        //===========
        // display list => VIEW
        public static void Display(List<Phone> listphone)
        {
            Sort(listphone);
            if (listphone.Count > 0)
                foreach (Phone phone in listphone)
                {
                    Console.WriteLine(phone.Name + "\t" + phone.Code + "\t" + phone.Address + "\t" + phone.Number);
                }
        }

        // display sortelist => VIEW
        public static void Display(SortedList<int, Phone> s_listphone)
        {
            Sort(listphone);
            if (s_listphone.Count > 0)
                for (int i = 0; i < s_listphone.Count; i++)
                    Console.WriteLine((i + 1) + " :  " + s_listphone[i].Name + "\t" + s_listphone[i].Code + "\t" + s_listphone[i].Address + "\t" + s_listphone[i].Number);
        }

     
        //==================
        // search subscribers with name input from keyboard
        static public SortedList<int,Phone> SearchName(List<Phone> listphone)
        {
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            string _name, kt = "false"; 
            int i=0;
            Console.Write("Nhap ten thue bao can tim:"); _name = Console.ReadLine();
            foreach (Phone phone in listphone)
            {
                if (phone.Name.Contains(_name))
                {
                    S_listphone.Add(i, phone);
                    i++;
                    kt = "true";
                }
            }
            if (kt == "false")
                Console.WriteLine("So dien thoai khong ton tai");
            return S_listphone;
        }

        //==================
        // search subscribers with phone number input from keyboard
        static public SortedList<int, Phone> SearchNumber(List<Phone> listphone)
        {
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            string _number, kt = "false";
            int i = 0;
            Console.Write("Nhap so dien thoai can tim can tim:"); _number = Console.ReadLine();
            foreach (Phone phone in listphone)
            {
                if (phone.Number.Contains(_number))
                {
                    Console.WriteLine(phone.Name + "\t" + phone.Code + "\t" + phone.Address + "\t" + phone.Number);
                    kt = "true";
                    S_listphone.Add(i, phone);
                    i++;
                }
                
            }
            if(kt=="false")
                Console.WriteLine("So dien thoai khong ton tai");
            return S_listphone;
        }
        //==============================================
        static void FuntionSearchName()
        {           
            listphone = XmlToList(filename);
            S_listphone = SearchName(listphone);
            Display(S_listphone);
        }
        static void FuntionSearchNumber()
        {
            listphone = XmlToList(filename);
            S_listphone =SearchNumber(listphone);
            Display(S_listphone);
        }
        //===============
        static void FuntionEdit()//sai
        {
            int count = 0, i = 0, number = 0;
            string _Name, _Code, _Address, choose;
            Console.Write(" chon so thu tu cua thue bao can sua:");
            try
            {
                do
                {
                    pos = Convert.ToInt32(Console.ReadLine());
                    count++;
                    if (count > 1)
                        Console.Write("Lua chon khong chinh xac");
                }
                while ((pos) > S_listphone.Count);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
           

            do
            {
                if (i > 0)
                {
                    Console.Write("\t\tNhap lai ten : ");
                }
                else

                    Console.Write("Moi nhap ten : ");
                _Name = Console.ReadLine();
                i++;
            }
            while (_Name.Length > 30);
            i = 0;
            //code
            do
            {
                if (i > 0)
                    Console.Write("\t\tNhap lai ma vung : ");
                else
                    Console.Write(" Moi nhap ma vung : ");
                _Code = Console.ReadLine();
                i++;
            }
            while (_Code.Length > 5);
            //address
            i = 0;
            do
            {
                if (i > 0)
                    Console.Write("\t\tNhap lai dia chi : ");
                else
                    Console.Write(" Moi nhap dia chi : ");
                _Address = Console.ReadLine();
                i++;
            }
            while (_Address.Length > 50);
            //number
            i = 0;
            do
            {
                try
                {
                    if (i > 0)
                        Console.Write("\t\tNhap lai so dien thoai : ");
                    else
                        Console.Write(" Moi nhap so dien thoai : ");
                    i++;
                    number = Convert.ToInt32(Console.ReadLine());

                }
                catch (Exception ex)
                {
                }
            }
            while (number < 4000000 || number > 4999999);
            //do
            //{
            //    Console.Write("Nhap ten thue bao can sua:"); name = Console.ReadLine();
            //    Console.Write("Nhap ma vung thue bao can sua:"); code = Console.ReadLine();
            //    Console.Write("Nhap dia chi thue bao can sua:"); address = Console.ReadLine();
            //    Console.Write("Nhap so dien thoai can sua:"); number = Console.ReadLine();
            //}
            //while (test(name, code, address, number) != 0);
            Console.Write("Ban co dong y sua khong?(Y/N):");
            choose = Console.ReadKey().KeyChar.ToString();
            if ((choose == "y") || (choose == "Y"))
            {
                Phone phone = new Phone(name, code, address, number);
                listphone.Remove(S_listphone[pos - 1]);
                listphone.Add(phone);
                CreateFile();
                ListToXml(listphone);
                Console.WriteLine("\n sua thue bao thanh cong");
            }
            if ((choose == "n") || (choose == "N"))
            {
                Menu();
            }
        }
        //================sai kiem tra khi khong ton tai
       
        //==========================
        // delete element and add infomations new into file xml
        static void FuntionDelete()
        {
            int count=0;
            string choose;
            Console.Write(" chon so thu tu cua thue bao can xoa:");
            try
            {
               do
                {
                    pos = Convert.ToInt32(Console.ReadLine());
                    count++;
                    if (count > 1)
                        Console.Write("Lua chon khong chinh xac");
                }
                while ((pos) > S_listphone.Count);
                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.Write(" Ban co dong y xoa khong(Y/N?):");
            choose = Console.ReadKey().KeyChar.ToString();
            if ((choose == "y") || (choose == "Y"))
            {
                listphone.Remove(S_listphone[pos - 1]);
                CreateFile();
                ListToXml(listphone);
                Console.WriteLine("\n xoa thue bao thanh cong");
            }
            if ((choose == "n") || (choose == "N"))
            {
                Menu();
            }
        }
        //===========
        public static void Sort(List<Phone> listphone)
        {
            try
            {
                listphone.Sort(Compare);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }       
        }
        public static int Compare(Phone x, Phone y)
        {
            string lastnameX,lastnameY;
            lastnameX = x.Name.Substring(x.Name.LastIndexOf(' ') + 1);
            lastnameY = y.Name.Substring(y.Name.LastIndexOf(' ') + 1);
            //return x.Name.CompareTo(y.Name);
            if (lastnameX.Equals(lastnameY))
            {
                return x.Name.CompareTo(y.Name);
            }
            return lastnameX.CompareTo(lastnameY);
        }
        //===================================================================================================
        static void Main(string[] args)
        {         
        lap:
            Menu();
            string ch;
            ch = Console.ReadLine().ToString();
            switch (ch)
            {
                case "1"://check
                    {
                        insert(); Console.ReadKey(); Console.Clear(); goto lap;
                    }
                case "2"://check
                    {
                        Console.WriteLine("||                   1. Tim kiem theo ten...           ||");
                        Console.WriteLine("||                   2. Tim kiem theo so dien thoai... ||");
                        string choose = Console.ReadLine();
                        if (choose == "1")
                        {
                            FuntionSearchName();
                            FuntionEdit();
                        }
                        if (choose == "2")
                        {
                            FuntionSearchNumber();
                            FuntionEdit();
                        }
                        Console.ReadKey(); Console.Clear(); goto lap;
                    }
                case "3"://check
                    {
                        Console.WriteLine("||                   1. Tim kiem theo ten...           ||");
                        Console.WriteLine("||                   2. Tim kiem theo so dien thoai... ||");
                        string choose;
                        choose = Console.ReadLine();
                        if (choose == "1")
                        {
                            FuntionSearchName();
                            FuntionDelete();
                        }
                        if (choose == "2")
                        {
                            FuntionSearchNumber();
                            FuntionDelete();
                        }
                        Console.ReadKey(); Console.Clear(); goto lap;
                    }
                case "4"://check
                    {
                        FuntionSearchName();
                        S_listphone.Clear();
                        Console.ReadKey(); Console.Clear(); goto lap;
                    }
                case "5"://check
                    {
                        FuntionSearchNumber();
                        Console.ReadKey(); Console.Clear(); goto lap;
                    }
                case "6"://check
                    {
                        List<Phone> listphone = new List<Phone>();
                        listphone = XmlToList(filename);
                        Display(listphone);
                        Console.ReadKey(); Console.Clear(); goto lap;
                    }
                case "7": break;//check
                default://check
                    {
                        Console.Write("Chuc nang khong dung!"); Console.ReadKey(); Console.Clear(); goto lap;
                    }
            }
        }
    }
}
